package com.ars.flight;

import com.ars.db.DBTools;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;

import javax.swing.*;
import java.net.URL;
import java.sql.ResultSet;
import java.util.ResourceBundle;

public class ShowFlightController implements Initializable {
    DBTools db = null;
    @FXML
    private TableView tableView;
    @FXML
    private TableColumn fidColumn;
    @FXML
    private TableColumn first_seats_remainColumn;
    @FXML
    private TableColumn business_seats_remainColumn;
    @FXML
    private TableColumn economy_seats_remainColumn;
    @FXML
    private TableColumn discountColumn;
    @FXML
    private TableColumn dateColumn;
    @FXML
    private TableColumn sidColumn;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        fidColumn.setCellValueFactory(new PropertyValueFactory<>("fid"));
        first_seats_remainColumn.setCellValueFactory(new PropertyValueFactory<>("first_seats_remain"));
        business_seats_remainColumn.setCellValueFactory(new PropertyValueFactory<>("business_seats_remain"));
        economy_seats_remainColumn.setCellValueFactory(new PropertyValueFactory<>("economy_seats_remain"));
        discountColumn.setCellValueFactory(new PropertyValueFactory<>("discount"));
        dateColumn.setCellValueFactory(new PropertyValueFactory<>("date"));
        sidColumn.setCellValueFactory(new PropertyValueFactory<>("sid"));

        tableView.setItems(getData());
    }

    private ObservableList getData() {
        ObservableList data = FXCollections.observableArrayList();
        String sql = "select * from flight";
        db = new DBTools();
        ResultSet rs = db.query(sql);
        try {
            while (rs.next()) {
                Flight flight = new Flight();
                flight.setFid(rs.getInt("fid"));
                flight.setFirst_seats_remain(rs.getInt("first_seats_remain"));
                flight.setBusiness_seats_remain(rs.getInt("business_seats_remain"));
                flight.setEconomy_seats_remain(rs.getInt("economy_seats_remain"));
                flight.setDiscount(rs.getFloat("discount"));
                flight.setDate(rs.getString("date"));
                flight.setSid(rs.getInt("sid"));

                data.add(flight);
            }
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "获取信息失败！", "错误", JOptionPane.ERROR_MESSAGE);
        } finally {
            db.close();
        }
        return data;
    }

}


